package ws

import (
	"context"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"konglu-pay/global"
	"konglu-pay/model"
)

type WebSocketHandler interface {
	Read(ws *WebSocketExecutor)
	Write(ws *WebSocketExecutor)
}

type WebSocketExecutor struct {
	*model.WsContent
	Context context.Context
	*websocket.Conn
	cancel  context.CancelFunc
	Handler WebSocketHandler
}

func (w *WebSocketExecutor) Done() {
	w.cancel()
}

func (w *WebSocketExecutor) ListenAndServe() {
	defer func(Coon *websocket.Conn) {
		err := Coon.Close()
		if err != nil {
		}
	}(w.Conn)
	go w.Handler.Read(w)
	go w.Handler.Write(w)
	w.listen()
}

func (w *WebSocketExecutor) listen() {
	select {
	case <-w.Context.Done():
		break
	}
}

func NewWebSocketExecutor(coon *websocket.Conn, handler WebSocketHandler, wsContent *model.WsContent) *WebSocketExecutor {
	ctx, cancel := context.WithCancel(context.Background())
	return &WebSocketExecutor{Context: ctx, Conn: coon, cancel: cancel, Handler: handler, WsContent: wsContent}
}

func WebSocketHandlerFunc(handler func(ctx *gin.Context, coon *websocket.Conn)) gin.HandlerFunc {
	return func(context *gin.Context) {
		if coon, err := global.UpGrader.Upgrade(context.Writer, context.Request, nil); err == nil {
			handler(context, coon)
		}
	}
}
